﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using GooNews.ViewModels;

namespace GooNews.Pages
{
  /// <summary>
  /// 
  /// </summary>
  public partial class OptionsPage 
  {
    bool _isTesting = false;

    /// <summary>
    /// Initializes a new instance of the <see cref="OptionsPage"/> class.
    /// </summary>
    public OptionsPage()
    {
      InitializeComponent();

      DataContext = App.ViewModel.Options;

      addButton.Click += new RoutedEventHandler(addButton_Click);
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
      base.OnNavigatedTo(e);
      App.ViewModel.ShowMemoryConsuption();
    }

    /// <summary>
    /// Handles the Click event of the addButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    void addButton_Click(object sender, RoutedEventArgs e)
    {
      if (!string.IsNullOrEmpty(searchFeedBox.Text))
      {
        App.ViewModel.Options.AddSearchFeedInfo(searchFeedBox.Text);
        searchFeedBox.Text = "";
        App.DoHaptic();
      }
    }

    /// <summary>
    /// Handles the Click event of the deleteButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    private void deleteButton_Click(object sender, RoutedEventArgs e)
    {
      var feed = (FeedInfo)((Button)sender).DataContext;
      App.ViewModel.Options.SearchFeedTypes.Remove(feed);
      App.DoHaptic();
    }

    /// <summary>
    /// This method is called when the hardware back key is pressed.
    /// </summary>
    /// <param name="e">Set e.Cancel to true to indicate that the request was handled by the application.</param>
    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
      base.OnBackKeyPress(e);
      foreach (var f in App.ViewModel.Options.SearchFeedTypes) f.Title = f.Title.Trim();
      App.ViewModel.Options.Save();
      App.ViewModel.RebuildFeeds();
      App.ViewModel.ReloadFeeds();
    }

    /// <summary>
    /// Handles the Click event of the testLoginButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    private void testLoginButton_Click(object sender, RoutedEventArgs e)
    {

      App.DoHaptic();
      if (!_isTesting)
      {
        testStatusBlock.Text = "Sending Credentials...";
        string ipLink = string.Format("https://www.instapaper.com/api/authenticate?username={0}&password={1}",
          HttpUtility.UrlEncode(App.ViewModel.Options.InstaPaperUserName),
          HttpUtility.UrlEncode(App.ViewModel.Options.InstaPaperPassword));

        var client = new WebClient();
        client.DownloadStringCompleted += (s, a) =>
          {
            if (!a.Cancelled && a.Error == null)
            {
              this.testStatusBlock.Text = "Credentials verified.";
            }
            else
            {
              this.testStatusBlock.Text = "Creditials not valid.";
            }
            _isTesting = false;
          };
        client.DownloadStringAsync(new Uri(ipLink));


      }
    }

    /// <summary>
    /// Handles the KeyUp event of the searchFeedBox control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
    private void searchFeedBox_KeyUp(object sender, KeyEventArgs e)
    {
      if (e.Key == Key.Enter)
      {
        // Fake addButton
        addButton_Click(null, null);
        this.Focus();
      }
    }

    /// <summary>
    /// Handles the KeyUp event of the instaPaperUserTextBox control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
    private void instaPaperUserTextBox_KeyUp(object sender, KeyEventArgs e)
    {
      if (e.Key == Key.Enter)
      {
        instaPaperPasswordBox.Focus();
      }
    }

    /// <summary>
    /// Handles the KeyUp event of the instaPaperPasswordBox control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
    private void instaPaperPasswordBox_KeyUp(object sender, KeyEventArgs e)
    {
      if (e.Key == Key.Enter)
      {
        testLoginButton_Click(null, null);
        this.Focus();
      }
    }

    /// <summary>
    /// Handles the SelectedChanged event of the SelectSwitch control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void SelectSwitch_SelectedChanged(object sender, EventArgs e)
    {
      App.DoHaptic();
    }
  }
}